/**
 * 
 */
package org.vsg.common.jobscheduler.web;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.quartz.SchedulerFactory;
import org.quartz.ee.servlet.QuartzInitializerListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.vsg.common.jobscheduler.service.impl.QuartzServiceImpl;

/**
 * @author Bill Vison
 *
 */
public class ScheFactoryIntegrateSpringListener implements ServletContextListener{
	
	/**
	 * set the logger for develope code , do not use System.print(ln) to out print message.
	 */
	protected static final Logger logger = LoggerFactory.getLogger(ScheFactoryIntegrateSpringListener.class);	

	
	@Override
	public void contextDestroyed(ServletContextEvent servletContextEvent) {
		// TODO Auto-generated method stub

		
	}

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		// TODO Auto-generated method stub
		
		ServletContext servletContext = servletContextEvent.getServletContext();
		try {
			SchedulerFactory factory = 
				(SchedulerFactory)servletContext.getAttribute( QuartzInitializerListener.QUARTZ_FACTORY_KEY );
			
			WebApplicationContext appContext = 
				(WebApplicationContext)servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
			
			String[] beansName = appContext.getBeanNamesForType(QuartzServiceImpl.class);
			
			logger.debug("Load the quartzServiceBean and set the singleton SchedulerFactory . ");
			
			if (beansName.length > 0) {
				QuartzServiceImpl impl = (QuartzServiceImpl)appContext.getBean(beansName[0]);
				impl.setSchedulerFactory( factory );
			} else {
				logger.debug("Did not set SchedulerFactory into QuartzService implement. ");				
			}

			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	

}
